package com.example.coursehub.user.service;

import com.example.coursehub.user.dto.UserDTO;
import com.example.coursehub.user.dto.UserRequestDTO;
import com.example.coursehub.user.entity.User;
import com.example.coursehub.user.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 用户服务业务逻辑层
 */
@Slf4j
@Service
public class UserService {

    private static final Logger log = LoggerFactory.getLogger(UserService.class);
    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;

    public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder) {
        this.userRepository = userRepository;
        this.passwordEncoder = passwordEncoder;
    }

    /**
     * 用户注册
     */
    @Transactional
    public UserDTO register(UserRequestDTO.RegisterRequest request) {
        // 检查用户账号是否已存在
        if (userRepository.existsByUserAccount(request.getUserAccount())) {
            throw new RuntimeException("用户账号已存在");
        }

        // 生成用户ID
        String userId = "U" + request.getUserAccount();
        
        // 创建用户实体
        User user = new User();
        user.setUserId(userId);
        user.setUserName(request.getUserName());
        user.setUserAccount(request.getUserAccount());
        user.setUserPassword(passwordEncoder.encode(request.getUserPassword()));
        user.setRole(request.getRole());
        user.setStatus(1); // 默认启用

        User savedUser = userRepository.save(user);
        log.info("用户注册成功: {}", savedUser.getUserAccount());
        
        return UserDTO.fromEntity(savedUser);
    }

    /**
     * 用户登录验证
     */
    public UserDTO login(UserRequestDTO.LoginRequest request) {
        Optional<User> userOpt = userRepository.findByUserAccount(request.getUserAccount());
        
        if (userOpt.isEmpty()) {
            throw new RuntimeException("用户不存在");
        }

        User user = userOpt.get();
        
        if (user.getStatus() == 0) {
            throw new RuntimeException("用户已被禁用");
        }

        if (!passwordEncoder.matches(request.getUserPassword(), user.getUserPassword())) {
            throw new RuntimeException("密码错误");
        }

        log.info("用户登录成功: {}", user.getUserAccount());
        return UserDTO.fromEntity(user);
    }

    /**
     * 根据用户ID查询用户
     */
    public UserDTO getUserById(String userId) {
        Optional<User> userOpt = userRepository.findById(userId);
        return userOpt.map(UserDTO::fromEntity).orElse(null);
    }

    /**
     * 根据用户账号查询用户
     */
    public UserDTO getUserByAccount(String userAccount) {
        Optional<User> userOpt = userRepository.findByUserAccount(userAccount);
        return userOpt.map(UserDTO::fromEntity).orElse(null);
    }

    /**
     * 批量查询用户
     */
    public List<UserDTO> getUsersByIds(List<String> userIds) {
        List<User> users = userRepository.findByUserIds(userIds);
        return users.stream()
                .map(UserDTO::fromEntity)
                .collect(Collectors.toList());
    }

    /**
     * 根据角色查询用户
     */
    public List<UserDTO> getUsersByRole(User.UserRole role) {
        List<User> users = userRepository.findByRole(role);
        return users.stream()
                .map(UserDTO::fromEntity)
                .collect(Collectors.toList());
    }

    /**
     * 查询所有启用的用户
     */
    public List<UserDTO> getActiveUsers() {
        List<User> users = userRepository.findActiveUsers();
        return users.stream()
                .map(UserDTO::fromEntity)
                .collect(Collectors.toList());
    }

    /**
     * 更新用户信息
     */
    @Transactional
    public UserDTO updateUser(String userId, UserRequestDTO.UpdateRequest request) {
        Optional<User> userOpt = userRepository.findById(userId);
        
        if (userOpt.isEmpty()) {
            throw new RuntimeException("用户不存在");
        }

        User user = userOpt.get();
        
        if (request.getUserName() != null) {
            user.setUserName(request.getUserName());
        }
        
        if (request.getUserPassword() != null) {
            user.setUserPassword(passwordEncoder.encode(request.getUserPassword()));
        }
        
        if (request.getRole() != null) {
            user.setRole(request.getRole());
        }
        
        if (request.getStatus() != null) {
            user.setStatus(request.getStatus());
        }

        User updatedUser = userRepository.save(user);
        log.info("用户信息更新成功: {}", updatedUser.getUserAccount());
        
        return UserDTO.fromEntity(updatedUser);
    }

    /**
     * 修改密码
     */
    @Transactional
    public void changePassword(String userId, UserRequestDTO.ChangePasswordRequest request) {
        Optional<User> userOpt = userRepository.findById(userId);
        
        if (userOpt.isEmpty()) {
            throw new RuntimeException("用户不存在");
        }

        User user = userOpt.get();
        
        if (!passwordEncoder.matches(request.getOldPassword(), user.getUserPassword())) {
            throw new RuntimeException("原密码错误");
        }

        user.setUserPassword(passwordEncoder.encode(request.getNewPassword()));
        userRepository.save(user);
        
        log.info("用户密码修改成功: {}", user.getUserAccount());
    }

    /**
     * 禁用用户
     */
    @Transactional
    public void disableUser(String userId) {
        Optional<User> userOpt = userRepository.findById(userId);
        
        if (userOpt.isEmpty()) {
            throw new RuntimeException("用户不存在");
        }

        User user = userOpt.get();
        user.setStatus(0);
        userRepository.save(user);
        
        log.info("用户已禁用: {}", user.getUserAccount());
    }

    /**
     * 启用用户
     */
    @Transactional
    public void enableUser(String userId) {
        Optional<User> userOpt = userRepository.findById(userId);
        
        if (userOpt.isEmpty()) {
            throw new RuntimeException("用户不存在");
        }

        User user = userOpt.get();
        user.setStatus(1);
        userRepository.save(user);
        
        log.info("用户已启用: {}", user.getUserAccount());
    }
}